/**
 * @todo 异步校验，校验用户名是否存在不能重复
 */
const app = require('../server')
const User = require('../../model/User')
const validate = require('validate.js');


const constraints = {
    name: {
        type: 'string',
        presence: {
            allowEmpty: false
        },
        length: {
            minimum: 1,
            maximum: 14
        }
    },
    account: {
        type: "string",
        presence: {
            allowEmpty: false,
        },
        format: {
            pattern: /[\da-zA-Z]{8,20}/,
            message: '只能是数字、小写英文字母、大写英文字母组成，长度最小8位，最长20位'
        }
    },
    password: {
        presence: {
            allowEmpty: false,
        },
        password: {}
    }
}
const whiteList = {
    name: true,
    account: true,
    password: true
}
app.post('user', async function (req, res) {
    console.log(req)
    // let res = null
    // try {
    //     data = validate.cleanAttributes(data, whiteList)
    //     await validate.async(data, constraints)
    //     res = await User.create(data)
    // } catch (e) {
    //     return e
    // }
    // return res.toJSON()
})

/** 
 * @todo put 是否能写一个统一的id校验？
 * */
// 只允许更改用户名
app.put('user', async function (id, data) {
    let res = null
    try {
        await validate.async({ name: data.name }, { name: constraints.name })
        res = await User.update(data, {
            where: {
                id
            }
        })
    } catch (e) {
        return e
    }
    return res.toJSON()
})

// 删除用户


// 修改密码
app.post('changepwd', async function (id, password) {
    let res = null
    try {
        await validate.async({ password }, { password: constraints.password })
        res = await User.create(data)
    } catch (e) {
        return e
    }
    return res.toJSON()
})